package com.atguigu.nio.zerocopy;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

public class NewIOClient {
    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("localhost",7001));
        String fileName = "protoc-3.6.1-win32.jpg";

        //得到一个文件的channel
        FileInputStream fileInputStream = new FileInputStream(fileName);
        FileChannel fileChannel = fileInputStream.getChannel();

        //准备发送
        long startTime = System.currentTimeMillis();

        //在linux下一个transferTo方法可以完成传输
        //在Windows下一次调用transferTo只能发送8m，就需要分段传输文件，而且要注意传输时的位置
        //transferTo底层使用到零拷贝
        long transferCount = fileChannel.transferTo(0, fileChannel.size(), socketChannel);

        long endTime = System.currentTimeMillis();

        System.out.println("发送的总的字节数=" + transferCount + "，耗时：" + (endTime - startTime));

        //关闭
        fileChannel.close();
    }
}
